import multer from 'multer'
import { BadRequest } from 'http-errors'
import OSS from 'ali-oss'
import MAO from 'multer-aliyun-oss'
import { RequestHandler } from 'express'

// 阿里云配置信息
export const config: OSS.Options = {
  region: process.env.ALIYUN_REGION,
  accessKeyId: process.env.ALIYUN_ACCESS_KEY_ID as string,
  accessKeySecret: process.env.ALIYUN_ACCESS_KEY_SECRET as string,
  bucket: process.env.ALIYUN_BUCKET,
}

export const client = new OSS(config)

// 自定义文件大小限制
export const MAX_FILE_SIZE = 5 * 1024 * 1024

// multer 配置信息(有bug，limits校验不通过也会上传OSS)
const upload = multer({
  storage: MAO({
    config,
    destination: 'uploads', // 自定义上传目录
  }),
  // limits: {
  //   fileSize: MAX_FILE_SIZE,
  // },
  fileFilter: (req, file, cb) => {
    const isImage = file.mimetype.startsWith('image')
    if (!isImage) {
      return cb(new BadRequest('只允许上传图片。'))
    }
    cb(null, true)
  },
})

/**
 * 使用 http 请求头中的 content-length 限制文件大小
 */
const fileSizeLimits: RequestHandler = (req, res, next) => {
  const contentLength = parseInt(req.headers['content-length'] as string)
  // 限制上传文件的大小为：5MB
  if (contentLength > 5 * 1024 * 1024) {
    return next(new BadRequest('文件大小不能超过5MB'))
  }
  next()
}

/**
 * 单文件上传，指定表单字段名为 file
 * @param req
 * @param res
 * @param next
 */
export const singleFileUpload: RequestHandler = (req, res, next) => {
  // 检查文件大小是否超出限制
  fileSizeLimits(req, res, (err) => {
    if (err) return next(err)
    upload.single('file')(req, res, next)
  })
}
